package com.bawei.common_module.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import java.lang.reflect.ParameterizedType

/**
 * 作者: 李韵佳
 * 日期: 2024/8/15
 * 时间: 14:51
 * 描述:
 */
abstract class BaseFragment<VM: ViewModel,D: ViewDataBinding>(private val layoutId:Int) :Fragment() {
    lateinit var viewModel: VM
    lateinit var binding:D

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding= DataBindingUtil.inflate(inflater,layoutId, container, false)
        return binding.root
    }
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        val type = javaClass.genericSuperclass as ParameterizedType
        val vmClass = type.actualTypeArguments[0] as Class<VM>
        viewModel= ViewModelProvider(this)[vmClass]

        initViews()

        dataObserver()
    }

    abstract fun dataObserver()

    abstract fun initViews()
    override fun onDestroy() {
        super.onDestroy()
        if(binding!=null){
            binding.unbind()
        }
    }

}